package uk.ac.nott.cs.g53dia;

import java.util.List;

import uk.ac.nott.cs.g53dia.Bee.Role;
import utils.Constants;
import utils.RandomGenerator;

public class FollowQueenAction implements Action {

  private static final float NOISE_PROB = 0.2f;

  public void execute(Environment env, Bee bee) throws ActionFailedException {
    if (bee.getRole() == Role.QUEEN) {
      throw new ActionFailedException("Cannot follow myself.");
    }
    List<Bee> beesInRange = env.getBeesForCommunication(bee.getPosition(), Bee.VIEW_RANGE + 1);
    boolean findQueen = false;
    for (Bee beeAux : beesInRange) {
      if (beeAux.getRole() == Role.QUEEN) {
        findQueen = true;
        int dx = beeAux.getPosition().x - bee.getPosition().x;
        int dy = beeAux.getPosition().y - bee.getPosition().y;
        if (dx < 0) {
          if (RandomGenerator.getRandomFloat() > NOISE_PROB) {
            bee.position.x--;
          }
        } else if (dx > 0) {
          if (RandomGenerator.getRandomFloat() > NOISE_PROB) {
            bee.position.x++;
          }
        } else {
          if (RandomGenerator.getRandomFloat() < NOISE_PROB) {
            bee.position.x += RandomGenerator.getRandomInt(3) - 1;
          }
        }
        if (dy < 0) {
          if (RandomGenerator.getRandomFloat() > NOISE_PROB) {
            bee.position.y--;
          }
        } else if (dy > 0) {
          if (RandomGenerator.getRandomFloat() > NOISE_PROB) {
            bee.position.y++;
          }
        } else {
          if (RandomGenerator.getRandomFloat() < NOISE_PROB) {
            bee.position.y += RandomGenerator.getRandomInt(3) - 1;
          }
        }
        Environment.moveBee(bee);
        bee.useEnergy(1);
        break;
      }
    }
    if (!findQueen)
      throw new ActionFailedException("Cannot see the queen.");
  }

  public String getCode() {
    return String.valueOf(Constants.FOLLOW_QUEEN_ACTION_CODE);
  }

}
